Javascript 扩展内置对象

在js中,内建对象的构造器函数(例如 Array, String, Object 和 Function )都是可以通过其原型来进行扩展的;

扩展一 inArray(string)

用于查询数组中是否存在某个特定的值

1
2
3
4
5
6
7
8
Array.prototype.inArray = function(string){
for(var i=0; i<this.length; i++){
if(this[i]===string){
return true;
}
}
return false;
}

扩展二 reverse()

用于翻转字符串

1
2
3
String.prototype.reverse = function(){
return Array.prototype.reverse.apply(this.split("")).join("");
}

扩展三: trim()

用于简化字符串,删除字符串两头的空格

1
2
3
4
5
if(typeof String.prototype.trim !== 'function'){
String.prototype.trim=function(){
return this.replace(/^\s+|\s+&/g,'');
}
}

trim()方法是ES5标准的一部分,但是在老式的浏览器中并没有得到支持

扩展四: shuffle()

用于将一个数组进行随机打乱

1
2
3
4
5
6
7
8
9
10
11
Array.prototype.shuffle=function(){
var randomSort=function(a,b){
return Math.random()>.5 ? -1 : 1;
}

return this.sort(randomSort);
}

// eg:
// var num=[1,2,3,4,5,6,7,8,9];
// console.log(num.shuffle());

注:如果想要通过原型为某个对象添加一个新属性,务必先检查一下该属性是否已经存在,避免当前浏览器已经支持相应的方法,我们又加以改写,导致的效果不一样而造成不必要的异常,如扩展三。

引自: 网易博客(奔跑吧~昭熙小乐)